<template>
  <div class="box-card">
    <div slot="header" class="cardHeader">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-plus"
        style="float: right;"
        v-permission="['MONITOR_GROUP_ADDGROUP_BUTTON']"
        @click="handleAddClick"
      >添加分组</el-button>
    </div>
    <el-input
      v-model.trim="filterText"
      size="small"
      prefix-icon="el-icon-search"
      placeholder="请输入搜索项"
      maxlength="30"
      style="margin: 16px 0 0 0"
    />
    <div class="left-title" />
    <el-tree
      ref="tree"
      empty-text="暂无数据"
      :style="{ '--lightOpacity': lightTheme }"
      class="left-tree"
      :data="tree"
      :props="defaultProps"
      :default-expand-all="false"
      :expand-on-click-node="false"
      :highlight-current="true"
      :current-node-key="currentKey"
      :filter-node-method="filterNode"
      node-key="id"
      :default-expanded-keys="expendData"
      @node-click="handleNodeClick"
      v-loading="treeloading"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <div>
          <i v-permission="['MONITOR_GROUP_EMPOWER_BUTTON']" class="el-icon-share" @click.stop="empower(data)"></i>
          <i v-permission="['MONITOR_GROUP_EDITGROUP_BUTTON']" class="el-icon-edit edit-btn" @click.stop="edit(data)"></i>
          <i v-permission="['MONITOR_GROUP_DELGROUP_BUTTON']" class="el-icon-delete del-btn" @click.stop="remove(data)"></i>
        </div>
      </span>
    </el-tree>
    <dtDialog
      :title="isAdd ? '新增分组' : '修改分组名称'"
      :visible.sync="dialogVisible"
      :lock-scroll="false"
      :append-to-body="true"
      :is-loading="loading"
      @closeDialog="onModalClosed"
      @comfirmBtn="onSubmit()"
    >
      <el-form
        ref="form"
        slot="content"
        label-width="130px"
        :model="form"
        :rules="rules"
      >
        <el-row>
          <el-col :span="24" v-if="!isAdd">
            <el-form-item label="分组编码" prop="groupCode">
              <el-input v-model.trim="form.groupCode" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分组名称" prop="groupName">
              <el-input
                v-model.trim="form.groupName"
                maxlength="10"
                placeholder="请输入分组名称"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </dtDialog>
    <userTableModal ref="userTableModal" />
    <personSelect
      v-if="allocationShow"
      ref="personPicker"
      v-model="personValue"
      :params="params"
      :search-user-params="params"
      :api="bussinessRoleManageApi"
      :selectedData="[]"
      :tag-visible="false"
      :reappear="true"
      :selected-data="select"
      @handleSelectData="selected" />
  </div>
</template>

<script>
import { getVideoGroup, addVideoGroup, editVideoGroup } from '@/api/videoFusion/videoManage'
import { countByGroupId, delVideoGroup, getByGroupIdToUserId, empowerUser } from '@/api/videoFusion/monitorGroup'
import { getRoleId } from '@/api/videoFusion/upstreamAccess'
import { getManagingOrgUserList, searchOrgName, searchUserName } from '@/framework/api/authCenter/bussinessRoleManage'
import { getUserListByUserIds } from '@/framework/api/affairManage/flowDetail/Config'
import userTableModal from './userTableModal'

export default {
  components: { userTableModal },
  data() {
    return {
      action: 1,
      filterText: '',
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentKey: '',
      expendData: [],
      treeloading: false,
      loading: false,
      dialogVisible: false,
      form: {
        groupCode: '',
        groupName: ''
      },
      isAdd: true,
      rules: {
        groupName: [{ required: true, message: '请输入分组名称', trigger: ['blur'] }],
        groupCode: [{ required: true, message: '请输入分组编码', trigger: ['blur'] }]
      },
      allocationShow: false,
      params: {
        roleId: ''
      },
      personValue: '',
      bussinessRoleManageApi: { getManagingOrgUserList, searchOrgName, searchUserName, getUserListByUserIds },
      select: [],
      groupId: ''
    }
  },
  computed: {
    lightTheme() {
      return `${this.$store.state.settings.theme}19`
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getData()
    getRoleId().then((res) => {
      this.params.roleId = res.data
    })
  },
  methods: {
    getData() {
      this.treeloading = true
      getVideoGroup().then((res) => {
        this.tree = res.data.map((item) => {
          return {
            label: `${item.groupName}(${item.groupCode})`,
            ...item
          }
        })
        this.currentKey = this.tree[0].id
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.currentKey)
          this.$emit('treeClick', this.tree[0])
        })
        this.treeloading = false
      }).finally(() => {
        this.treeloading = false
      })
    },
    handleNodeClick(data) {
      this.$emit('treeClick', { ...data, belongToType: this.action })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    empower(data) {
      // this.$refs.userTableModal.open(data)
      this.allocationShow = false
      this.groupId = data.id
      this.personValue = ''
      if (this.params.roleId) {
        setTimeout(() => {
          this.allocationShow = true
          getByGroupIdToUserId(this.groupId).then((res) => {
            this.personValue = res.data.join(',')
            setTimeout(() => {
              this.$refs.personPicker.show()
            }, 10)
          })
        }, 10)
      }
    },
    edit(data) {
      this.isAdd = false
      this.dialogVisible = true
      this.form = { ...data }
    },
    remove(data) {
      countByGroupId({ groupId: data.id }).then((res) => {
        let message
        if (res.data > 0) {
          message = '该监控分组下存在监控，是否确认删除？'
        } else {
          message = '是否要删除该监控分组？'
        }
        this.$dtModal.confirm(message).then(() => {
          delVideoGroup(data.id).then((res) => {
            this.$message.success(res.message)
            this.getData()
          })
        })
      })
    },
    handleAddClick() {
      this.isAdd = true
      this.dialogVisible = true
    },
    onModalClosed() {
      this.$refs.form.resetFields()
      this.form = {
        groupCode: '',
        groupName: ''
      }
    },
    onSubmit() {
      this.$refs.form.validate((result, message) => {
        if (result) {
          this.loading = true
          if (this.isAdd) {
            addVideoGroup(this.form).then((res) => {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.loading = false
              this.getData()
            }).catch(() => {
              this.loading = false
            })
          } else {
            editVideoGroup(this.form).then((res) => {
              this.$message.success(res.message)
              this.dialogVisible = false
              this.loading = false
              this.getData()
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    selected(select) {
      this.select = select
      const params = {
        groupId: this.groupId
      }
      params.userIds = this.select.map((item) => {
        return item.userId
      })
      // console.log(params)
      empowerUser(params).then((res) => {
        this.$dtModal.msgSuccess(res.message)
        this.groupId = ''
        this.personValue = ''
        this.allocationShow = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.left-title {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 16px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding: 0 8px;
  .edit-btn {
    margin: 0 8px;
  }
  .del-btn {
    color: #F56C6C;
  }
}
.el-dropdown-link {
  margin-right: 8px;
  display: block;
  // width: 16px;
  // height: 16px;
  text-align: center;
  font-size: 14px;
}
::v-deep .el-tree-node__expand-icon.is-leaf {
  display: none;
}
</style>

